package com.secondkill.exception;

import com.secondkill.result.CodeMsg;
import com.secondkill.result.Result;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;


/**
 * Created by IBM on 2018/7/5.
 */
// 通过下面的两个配置， 就可以实现类似Controller了
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    // 配置默认拦截所有的Exception
    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request, Exception ex) {

        if (ex instanceof GlobalException) {
            GlobalException globalException = (GlobalException)ex;
            return Result.error(globalException.getCodeMsg());
        } else if (ex instanceof BindException) {
            BindException bindException = (BindException)ex;
            String errorMsg = bindException.getAllErrors().stream().map(error -> {
                return error.getDefaultMessage();
            }).collect(Collectors.joining(","));
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(errorMsg));
        } else {
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
